package cn.edu.buaa.treehole.service;

import cn.edu.buaa.treehole.dao.SignatureDao;
import cn.edu.buaa.treehole.dao.exception.DaoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class SignatureService {
    private final Random random = new Random();
    private final SignatureDao signatureDao;
    private final char[] pool = new char[]{
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',

            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',

            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',

            'w', 'x', 'y', 'z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '!', '@',

            '#', '$', '%', '^', '&', '<', '>', '?',
            '[', ']', '{', '}', ':', ';', '|', ',',

            '(', ')', '-', '+', '=', '_', '\\', '/',
    };

    @Autowired
    public SignatureService(SignatureDao signatureDao) {
        this.signatureDao = signatureDao;
    }

    public String nextSignature(long pid) throws DaoException {
        while(true) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < 16; i++) {
                stringBuilder.append(pool[random.nextInt(pool.length)]);
            }
            String ret = stringBuilder.toString();
            if (!signatureDao.containSignature(pid, ret)) {
                return ret;
            }
        }
    }
}
